#!/usr/bin/python
# -*- coding: cp1250 -*-

import glob, re, sys, pepe.p_txt.bigtxt as bt

def loadKeyRowFile(fileMask, cIndex):
    '''
    Loading file(s) data to key -> row dictionary structure
    Key is value in column with index cIndex
    '''
    data = {}
    # indexing starting at 1 (not 0); other utilities do so e.g. csvh.py
    cIndex = int(cIndex) - 1
    # loading all csv_ files in directory into one dictionary
    for inpfile in glob.glob(fileMask):
        for line in bt.lines(inpfile):
            line = re.sub('\n','',line) 
            cols = line.split('\t')
            data[cols[cIndex]] = line[:]
    print len(data), ' rows has been loaded'
    return data

def main(fileMask, keysFile='keys.txt', cIndex=1):
    '''
    Lookup searches information (rows) in data text files via lookup values (keys). 
    If identical key value is found in data file, this row will be printed out to output.
    In case that scanned data files has more than one row with same key, last such row will be used.

    Data files are expected to be tab delimited text files.
    
    Syntax: lookup <fileMask=string> [keysFile=string] [cIndex=int]

    Mandatory parameters:
        fileMask = ...

    Optional parameters (with default values):
        keysFile = "keys.txt" 
        cIndex   = 1 (key is in first column of scanned data files)
    '''
    try:
        data = loadKeyRowFile(fileMask, cIndex)
        if len(data) < 1:
            msg = 'Please copy data files here before runnnig lookup.'
            print msg
            of = open(re.sub(' ','_', msg) + 'txt', 'w')
        else:
            of = open("%s_values.txt" % (keysFile), 'w')
            # lookup of desired rows - see match in Module description
            try:
                for line in bt.lines(keysFile):
                    _id = line.strip()
                    _id = re.sub('\n','',_id)
                    if data.has_key(_id):
                        of.write("%s\t%s\n" % (_id, data[_id]))
                    else:
                        of.write("%s\t%s\n" % (_id, "_"))
            except IOError:
                # in case of invalid lookup filename given
                print 'File', keysFile, 'does not exists or could not read!'
        of.close()
    except IndexError:
        # in case of invalid column-with-id number given
        print 'Index of column with row ID (', cIndex, ') is wrong.'

if __name__ == "__main__":
    ''' '''
    if len(sys.argv) == 2:
        main(fileMask=sys.argv[1])
    elif len(sys.argv) == 3:
        main(fileMask=sys.argv[1], keysFile=sys.argv[2])
    elif len(sys.argv) == 4:
        main(fileMask=sys.argv[1], keysFile=sys.argv[2], cIndex=sys.argv[3])
    else:
        print main.__doc__
